<template>
  <div class="community-page">
    <!-- 顶部导航 -->
    <van-nav-bar title="维权社区" fixed>
      <template #right>
        <van-icon name="search" size="18" @click="$router.push('/search')" />
      </template>
    </van-nav-bar>

    <!-- 分类导航 -->
    <div class="category-nav">
      <van-tabs v-model:active="activeCategory" @change="onCategoryChange" sticky>
        <van-tab title="全部" name="all"></van-tab>
        <van-tab title="职场纠纷" name="workplace"></van-tab>
        <van-tab title="消费维权" name="consumer"></van-tab>
        <van-tab title="租房矛盾" name="housing"></van-tab>
        <van-tab title="其他" name="other"></van-tab>
      </van-tabs>
    </div>

    <!-- 筛选栏 -->
    <div class="filter-bar">
      <div class="filter-item" @click="showStatusFilter = true">
        <span>{{ statusFilterText }}</span>
        <van-icon name="arrow-down" />
      </div>
      <div class="filter-item" @click="showSortFilter = true">
        <span>{{ sortFilterText }}</span>
        <van-icon name="arrow-down" />
      </div>
      <div class="publish-btn" @click="goToPublish">
        <van-icon name="edit" />
        <span>发布</span>
      </div>
    </div>

    <!-- 帖子列表 -->
    <div class="post-list">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <div
            v-for="post in postList"
            :key="post.id"
            class="post-item"
            @click="goToPostDetail(post.id)"
          >
            <!-- 帖子头部 -->
            <div class="post-header">
              <div class="user-info">
                <img :src="post.avatar || defaultAvatar" class="avatar" />
                <div class="user-details">
                  <div class="nickname">{{ post.nickname || '匿名用户' }}</div>
                  <div class="post-time">{{ formatTime(post.createTime) }}</div>
                </div>
              </div>
              <div class="post-status">
                <span v-if="post.isResolved" class="status-tag resolved">已解决</span>
                <span v-else class="status-tag pending">求助中</span>
              </div>
            </div>

            <!-- 帖子内容 -->
            <div class="post-content">
              <div class="post-title">{{ post.title }}</div>
              <div class="post-summary">{{ post.content }}</div>
              
              <!-- 图片 -->
              <div v-if="post.images && post.images.length" class="post-images">
                <img
                  v-for="(image, index) in post.images.slice(0, 3)"
                  :key="index"
                  :src="image"
                  class="post-image"
                  @click.stop="previewImage(post.images, index)"
                />
                <div v-if="post.images.length > 3" class="more-images">
                  +{{ post.images.length - 3 }}
                </div>
              </div>

              <!-- 标签 -->
              <div v-if="post.tags" class="post-tags">
                <span
                  v-for="tag in post.tags.split(',')"
                  :key="tag"
                  class="tag"
                >
                  {{ tag }}
                </span>
              </div>
            </div>

            <!-- 帖子底部 -->
            <div class="post-footer">
              <div class="post-stats">
                <span class="stat-item">
                  <van-icon name="eye-o" />
                  {{ post.viewCount }}
                </span>
                <span class="stat-item">
                  <van-icon name="chat-o" />
                  {{ post.commentCount }}
                </span>
              </div>
              <div class="post-actions">
                <div
                  class="action-item"
                  :class="{ active: post.isLiked }"
                  @click.stop="toggleLike(post)"
                >
                  <van-icon :name="post.isLiked ? 'good-job' : 'good-job-o'" />
                  <span>{{ post.likeCount }}</span>
                </div>
                <div
                  class="action-item"
                  :class="{ active: post.isCollected }"
                  @click.stop="toggleCollect(post)"
                >
                  <van-icon :name="post.isCollected ? 'star' : 'star-o'" />
                  <span>收藏</span>
                </div>
              </div>
            </div>
          </div>
        </van-list>
      </van-pull-refresh>
    </div>

    <!-- 状态筛选弹窗 -->
    <van-action-sheet
      v-model:show="showStatusFilter"
      :actions="statusFilterOptions"
      @select="onStatusFilterSelect"
      cancel-text="取消"
    />

    <!-- 排序筛选弹窗 -->
    <van-action-sheet
      v-model:show="showSortFilter"
      :actions="sortFilterOptions"
      @select="onSortFilterSelect"
      cancel-text="取消"
    />

    <!-- 浮动发布按钮 -->
    <div class="floating-publish-btn" @click="goToPublish">
      <van-icon name="plus" />
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab" @change="onTabChange">
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="chat-o" to="/community">社区</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/templates">工具</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showImagePreview } from 'vant'
import { useUserStore } from '@/stores/user'
import { getPostList, likePost, collectPost } from '@/api/community'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const activeCategory = ref('all')
const activeTab = ref(1)
const refreshing = ref(false)
const loading = ref(false)
const finished = ref(false)
const showStatusFilter = ref(false)
const showSortFilter = ref(false)

// 筛选条件
const filters = reactive({
  status: 'all', // all, pending, resolved
  sort: 'latest' // latest, hot, like
})

// 帖子列表
const postList = ref([])
const defaultAvatar = 'https://img.yzcdn.cn/vant/cat.jpeg'

// 筛选选项
const statusFilterOptions = [
  { name: '全部状态', value: 'all' },
  { name: '求助中', value: 'pending' },
  { name: '已解决', value: 'resolved' }
]

const sortFilterOptions = [
  { name: '最新发布', value: 'latest' },
  { name: '最多回复', value: 'hot' },
  { name: '最多点赞', value: 'like' }
]

// 计算属性
const statusFilterText = computed(() => {
  const option = statusFilterOptions.find(item => item.value === filters.status)
  return option ? option.name : '全部状态'
})

const sortFilterText = computed(() => {
  const option = sortFilterOptions.find(item => item.value === filters.sort)
  return option ? option.name : '最新发布'
})

// 分页参数
const pageParams = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 方法
const onCategoryChange = (name) => {
  activeCategory.value = name
  refreshPostList()
}

const onLoad = () => {
  loadPosts()
}

const onRefresh = () => {
  refreshing.value = true
  postList.value = []
  finished.value = false
  pageParams.current = 1
  loadPosts().finally(() => {
    refreshing.value = false
  })
}

const loadPosts = async () => {
  loading.value = true
  
  try {
    // 构建查询参数
    const params = {
      current: pageParams.current,
      size: pageParams.size,
      categoryId: getCategoryId(activeCategory.value),
      status: filters.status === 'all' ? null : (filters.status === 'resolved' ? 1 : 0),
      sortBy: filters.sort
    }
    
    console.log('加载帖子参数:', params)
    
    const response = await getPostList(params)
    console.log('帖子列表响应:', response)
    
    if (response.code === 200) {
      const data = response.data
      const newPosts = data.records || data || []
      
      // 处理帖子数据，确保字段完整
      const processedPosts = newPosts.map(post => ({
        ...post,
        avatar: post.avatar || defaultAvatar,
        nickname: post.isAnonymous ? '匿名用户' : (post.nickname || '用户'),
        images: post.images ? (typeof post.images === 'string' ? post.images.split(',') : post.images) : [],
        tags: post.tags || '',
        isLiked: post.isLiked || false,
        isCollected: post.isCollected || false,
        viewCount: post.viewCount || 0,
        likeCount: post.likeCount || 0,
        commentCount: post.commentCount || 0,
        collectCount: post.collectCount || 0
      }))
      
      if (pageParams.current === 1) {
        postList.value = processedPosts
      } else {
        postList.value.push(...processedPosts)
      }
      
      // 更新分页信息
      pageParams.total = data.total || 0
      pageParams.current++
      
      // 检查是否还有更多数据
      if (processedPosts.length < pageParams.size) {
        finished.value = true
      }
    } else {
      showToast(response.message || '加载失败')
      finished.value = true
    }
  } catch (error) {
    console.error('加载帖子失败:', error)
    showToast('网络错误，请重试')
    finished.value = true
  } finally {
    loading.value = false
  }
}

// 获取分类ID的辅助函数
const getCategoryId = (category) => {
  const categoryMap = {
    'all': null,
    'workplace': 1,
    'consumer': 2, 
    'housing': 3,
    'other': 4
  }
  return categoryMap[category]
}

const refreshPostList = () => {
  postList.value = []
  finished.value = false
  pageParams.current = 1
  loadPosts()
}

const onStatusFilterSelect = (action) => {
  filters.status = action.value
  showStatusFilter.value = false
  refreshPostList()
}

const onSortFilterSelect = (action) => {
  filters.sort = action.value
  showSortFilter.value = false
  refreshPostList()
}

const goToPublish = () => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    router.push('/login')
    return
  }
  router.push('/community/publish')
}

const goToPostDetail = (postId) => {
  router.push(`/community/post/${postId}`)
}

const toggleLike = async (post) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }
  
  try {
    await likePost(post.id)
    post.isLiked = !post.isLiked
    post.likeCount += post.isLiked ? 1 : -1
    showToast(post.isLiked ? '点赞成功' : '取消点赞')
  } catch (error) {
    console.error('点赞操作失败:', error)
    showToast('操作失败')
  }
}

const toggleCollect = async (post) => {
  if (!userStore.isLoggedIn) {
    showToast('请先登录')
    return
  }
  
  try {
    await collectPost(post.id)
    post.isCollected = !post.isCollected
    post.collectCount += post.isCollected ? 1 : -1
    showToast(post.isCollected ? '收藏成功' : '取消收藏')
  } catch (error) {
    console.error('收藏操作失败:', error)
    showToast('操作失败')
  }
}

const previewImage = (images, startPosition) => {
  showImagePreview({
    images,
    startPosition,
    closeable: true
  })
}

const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return `${Math.floor(diff / 3600000)}小时前`
  if (diff < 2592000000) return `${Math.floor(diff / 86400000)}天前`
  
  return timeStr.split(' ')[0]
}

const onTabChange = (index) => {
  activeTab.value = index
}

onMounted(() => {
  loadPosts()
})
</script>

<style scoped>
.community-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 50px;
}

.category-nav {
  background: white;
  position: sticky;
  top: 46px;
  z-index: 99;
}

.filter-bar {
  display: flex;
  align-items: center;
  background: white;
  padding: 12px 16px;
  border-bottom: 1px solid #eee;
  gap: 16px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #646566;
  cursor: pointer;
}

.publish-btn {
  margin-left: auto;
  display: flex;
  align-items: center;
  gap: 4px;
  background: #1989fa;
  color: white;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 14px;
  cursor: pointer;
}

.post-list {
  padding: 8px 0;
}

.post-item {
  background: white;
  margin-bottom: 8px;
  padding: 16px;
  cursor: pointer;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
}

.nickname {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 2px;
}

.post-time {
  font-size: 12px;
  color: #969799;
}

.status-tag {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 4px;
}

.status-tag.resolved {
  background: #f6ffed;
  color: #52c41a;
}

.status-tag.pending {
  background: #fff7e6;
  color: #ff976a;
}

.post-content {
  margin-bottom: 12px;
}

.post-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  line-height: 1.4;
  margin-bottom: 8px;
}

.post-summary {
  font-size: 14px;
  color: #646566;
  line-height: 1.5;
  margin-bottom: 12px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.post-images {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  position: relative;
}

.post-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
}

.more-images {
  position: absolute;
  right: 8px;
  bottom: 8px;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.post-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag {
  font-size: 12px;
  padding: 2px 8px;
  background: #f0f9ff;
  color: #1989fa;
  border-radius: 4px;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.post-stats {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
}

.post-actions {
  display: flex;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #969799;
  cursor: pointer;
  transition: color 0.2s;
}

.action-item.active {
  color: #1989fa;
}

.floating-publish-btn {
  position: fixed;
  bottom: 80px;
  right: 20px;
  width: 56px;
  height: 56px;
  background: #1989fa;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.4);
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s ease;
}

.floating-publish-btn:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 16px rgba(25, 137, 250, 0.6);
}

.floating-publish-btn .van-icon {
  color: white;
  font-size: 24px;
}
</style>
